package org.jeecg.zhenxuan.Controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jeecg.zhenxuan.CommonUtils.SignatureUtil;
import org.jeecg.zhenxuan.Entity.PointFlow;
import org.jeecg.zhenxuan.Entity.UsersPoint;
import org.jeecg.zhenxuan.Repository.PointFlowRepository;
import org.jeecg.zhenxuan.Service.PointFlowAddService;
import org.jeecg.zhenxuan.Service.UserAddService;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

//import org.junit.Test;

@RestController
public class PointAddController {

    @Autowired
    private UserAddService userService;

    @Autowired
    private PointFlowAddService pointFlowService;


    /**
     * add by 2019年12月13日 星期五
     */
    @Autowired
    private PointFlowRepository pointFlowRepository;


    /**
     * 添加豆子
     * @param userNo
     * @param count
     * @return
     */
    @ResponseBody
    @RequestMapping("/addPoint")
    @Transactional
    public JSONObject addPointByOpenId(String userNo, String boNo, Integer count, String ts, String sign) {
        JSONObject result = new JSONObject();

        //非空判断
        if (StringUtils.isBlank(userNo) || count == null || StringUtils.isBlank(ts) || StringUtils.isBlank(sign) || StringUtils.isBlank(boNo) ) {
            result.put("status", 1);
            result.put("message", "参数为空！");
            return result;
        }
        try{
            //数字判断,并判断取值范围
            if(count < 0){
                result.put("status", 1);
                result.put("message", "豆子数量格式不能是负数");
                return result;
            }
        }catch (Exception e){
            result.put("status", 1);
            result.put("message", "豆子数量格式不正确");
            return result;
        }

        //生成签名
        JSONObject json = new JSONObject();
        json.put("userNo",userNo);
        json.put("boNo",boNo);
        json.put("totalPoint",count);
        json.put("ts",ts);
        //md5key
        String md5Key = "xuanzhen";
        String mySign = SignatureUtil.makeSignature(json,md5Key);

        //检验签名
        if(!mySign.equals(sign)){
            result.put("status", 1);
            result.put("message", "签名错误");
            return result;
        }

        try {
            //操作user表豆子总数，添加豆子
            UsersPoint user = userService.updateUser(userNo, count,"add");

            //添加失败，返回为null，事务回滚，返回响应
            if(user == null){
                //事务回滚
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                //响应
                result.put("status", 1);
                result.put("message", "未查询到用户数据");
                return result;
            }

            //添加操作明细
            PointFlow pointFlow = pointFlowService.savePointFlow(userNo, count, "add");

            //响应信息
            result.put("status", 0);
            result.put("message", "添加成功");
            result.put("point",user.getPointTotal());
            result.put("sn",pointFlow.getId());

        } catch (Exception e) {
            //发生异常
            //事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.put("status",2);
            result.put("message", "操作失败");
        }
        return result;
    }

    /**
     * 撤销添加豆子
     * @param openId
     * @param pointFlowId
     * @return
     */
    @RequestMapping("/revokeAddPoint")
    @ResponseBody
    @Transactional
    public JSONObject revokeAddPoint(String openId, String pointFlowId){
        JSONObject result = new JSONObject();
        JSONArray array = new JSONArray();
        //非空判断
        if(openId == null){
            result.put("status", "F");
            result.put("statusinformation", "参数为空！");
            return result;
        }

        try{
            if(pointFlowId == null){
                //如果明细id为空，获得最后一条添加记录
                pointFlowId = pointFlowService.getLastPointFlowId(openId);
            }


            //获得加豆子明细
            PointFlow pointFlow = pointFlowService.getPointFlowById(pointFlowId,"add");

            //获得明细失败，事务回滚，返回响应
            if(pointFlow == null){
                //事务回滚
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                //响应
                result.put("status", "F");
                result.put("statusinformation", "未查询到操作明细");
                return result;
            }

            //操作user表豆子总数，减少豆子
            UsersPoint user = userService.updateUser(openId, pointFlow.getCount(),"reduce");

            //减少豆子失败，返回为null，事务回滚
            if(user == null){
                //事务回滚
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                //响应
                result.put("status", "F");
                result.put("statusinformation", "未查询用户数据");
                return result;
            }

            //添加撤销加豆子明细
            //PointFlow pointFlow = pointFlowService.savePointFlow(addPointFlow.getOpenId(), addPointFlow.getCount(), "撤销添加");

            //删除添加豆子的操作明细记录
            pointFlowService.removeById(pointFlowId);
            //响应信息
            result.put("status", "T");
            result.put("statusinformation", "撤销添加成功");



        }catch (Exception e){
            //发生异常
            //事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.put("status", "F");
            result.put("statusinformation", "操作失败");
        }

        return result;
    }

    /**
     * 分页查询豆子流水明细
     * @param userNo openid
     * @param pageIndex 当前页码
     * @param elementCount 每页显示的数量
     * @return
     */
    @RequestMapping("/listPointFlowDetail")
    @ResponseBody
    public JSONObject listPointFlowDetail(String userNo, String pageIndex, String elementCount, String ts, String sign , @RequestParam(defaultValue = "default")String channel){

        JSONObject result = new JSONObject();

        //非空判断
        if(userNo == null || pageIndex == null || elementCount ==null){
            result.put("status", 1);
            result.put("message", "参数为空！");
            return result;
        }


        //生成签名
        JSONObject json = new JSONObject();
        json.put("userNo",userNo);
        json.put("pageIndex",pageIndex);
        json.put("elementCount",elementCount);
        json.put("ts",ts);
        String md5Key = "xuanzhen";
        String mySign = SignatureUtil.makeSignature(json,md5Key);


        //检验签名
        if(!mySign.equals(sign)){
            result.put("status", 1);
            result.put("message", "签名错误");
            return result;
        }

        try{

            //调用分页查询方法
//            JSONObject jsonObject = pointFlowService.listPointFlowDetail(userNo, pageIndex, elementCount);
            JSONObject jsonObject = pointFlowService.listPointFlowDetailStd(userNo,channel , pageIndex, elementCount);

            result.put("status", 0);
            result.put("message", "查询成功");
            result.put("result",jsonObject);

        }catch (Exception e){
            result.put("status", 2);
            result.put("message", "查询失败");
        }

        return result;
    }



}
